﻿using System.Linq;
using Microsoft.AspNetCore.Mvc;
using OAuthApp.Data;
using Swashbuckle.AspNetCore.Annotations;
using OAuthApp.Filters;
using OAuthApp.Services;
using Microsoft.EntityFrameworkCore;
using System;

namespace OAuthApp.Apis
{
    [SwaggerTag("应用发布版本")]
    [ServiceFilter(typeof(ApiRequestLoggingAttribute))]
    public class AppVersionsController : BaseController
    {
        private readonly AppDbContext _context;

        public AppVersionsController(AppDbContext context)
        {
            _context = context;
        }

        [HttpGet("{appId}")]
        [SwaggerOperation(OperationId = "AppVersions")]
        [EncryptResultFilter]
        public ActionResult GetAppVersion(int skip,
            int take)
        {
            var q = _context.AppVersions.Where(x => x.AppID == AppID)
                .AsQueryable();

            var total = q.Count();

            var data = q.OrderByDescending(x => x.ID)
                .Skip(skip)
                .Take(take)
                .ToList();

            return OK(new
            {
                total,
                data
            });
        }

        [HttpPut("{appId}")]
        [SwaggerOperation(OperationId = "AppVersionPut")]
        [EncryptResultFilter]
        public IActionResult Put(long appId, AppVersion value)
        {
            if (value.UserID != UserID && !IsAdmin)
            {
                return Error("权限不足");
            }

            var appVersion = _context.AppVersions.FirstOrDefault(x => x.ID == value.ID);

            appVersion.Tag = value.Tag;
            appVersion.Description = value.Description;

            try
            {
                _context.SaveChanges();
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }

            return OK(true);
        }
    }
}
